package cn.itsource.ymcc.service.impl;

import cn.itsource.ymcc.domain.CourseOrder;
import cn.itsource.ymcc.domain.CourseOrderItem;
import cn.itsource.ymcc.dto.OrderDto;
import cn.itsource.ymcc.mapper.CourseOrderItemMapper;
import cn.itsource.ymcc.mapper.CourseOrderMapper;
import cn.itsource.ymcc.service.ICourseOrderService;
import cn.itsource.ymcc.util.AssertUtil;
import cn.itsource.ymcc.util.CodeGenerateUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author whale.chen
 * @since 2023-03-08
 */
@Service
public class CourseOrderServiceImpl extends ServiceImpl<CourseOrderMapper, CourseOrder> implements ICourseOrderService {

    @Autowired
    private CourseOrderItemMapper courseOrderItemMapper;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 正常下单
     * @param orderDto
     * @return
     */
    @Transactional
    @Override
    public String placeOrder(OrderDto orderDto) {
        //执行下订单业务之前，先校验redis中是否存在token这个key
        AssertUtil.isTrue(StringUtils.hasText(orderDto.getToken()), "非法操作！");
        AssertUtil.isTrue(redisTemplate.hasKey(orderDto.getToken()), "请勿重复提交订单！");

        //1.封装一个CourseOrder对象
        CourseOrder courseOrder = new CourseOrder();
        courseOrder.setDiscountAmount(orderDto.getDiscountAmount());
        courseOrder.setUserId(orderDto.getLoginId());
        //设置订单编号
        String orderSn = CodeGenerateUtils.generateOrderSn(orderDto.getLoginId());
        courseOrder.setOrderNo(orderSn);
        courseOrder.setTitle("普通订单");

        //统计总金额、总数量
        Double totalAmount = 0D;
        Integer totalCount = 0;
        for (CourseOrderItem courseOrderItem : orderDto.getCourseOrderItems()) {
            totalAmount += courseOrderItem.getPrice().doubleValue() * courseOrderItem.getCount();
            totalCount += courseOrderItem.getCount();
        }
        courseOrder.setTotalAmount(new BigDecimal(totalAmount));
        courseOrder.setTotalCount(totalCount);
        //支付金额 = 总金额 - 优惠金额
        courseOrder.setPayAmount(new BigDecimal(totalAmount - orderDto.getDiscountAmount().doubleValue()));

        //保存订单主表数据，返回主键
        baseMapper.insert(courseOrder);

        //2.处理订单明细条目
        for (CourseOrderItem courseOrderItem : orderDto.getCourseOrderItems()) {
            courseOrderItem.setOrderNo(orderSn);
            courseOrderItem.setAmount(new BigDecimal(courseOrderItem.getPrice().doubleValue() * courseOrderItem.getCount()));
            courseOrderItem.setOrderId(courseOrder.getId());
            courseOrderItemMapper.insert(courseOrderItem);
        }

        //3.推送站内信
//        MessageDto messageDto = new MessageDto();
//        messageDto.setTitle("下单成功");
//        List<String> courseNames = orderDto.getCourseOrderItems().stream().map(coi -> coi.getCourseName()).collect(Collectors.toList());
//        messageDto.setContent("亲爱的用户您好，您购买的"+String.join("，",courseNames)+"已下单成功，订单编号为：" + orderSn + "，请尽快支付！");
//        messageDto.setStationDtoList(Arrays.asList(
//                new MessageDto.StationDto(orderDto.getLoginId(), "订单消息")
//        ));
//        Message<String> message = MessageBuilder.withPayload(JSON.toJSONString(messageDto)).build();
        //发站内信
//        rocketMQTemplate.sendOneWay(
//                Cons.Message.TOPIC_MESSAGE+":"+Cons.Message.TAGS_MESSAGE_STATION,
//                message
//        );

        //4.删除redis中这个token
        redisTemplate.delete(orderDto.getToken());

        return orderSn;
    }
}
